package org.jeecg.modules.yw.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.yw.entity.EnterPrise;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Api(tags = "工人管理")
@RestController
@RequestMapping("/yw/worker")
@Slf4j
public class WorkerController extends JeecgController<EnterPrise, EnterPriseService> {
    @Autowired
    private EnterPriseService enterPriseService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @ApiOperation(value = "获取工人分页列表")
    @GetMapping("/page")
    public Result page(@RequestParam(value = "mobile", required = false) String mobile,
                       @RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "position", required = false) String position,
                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize ) {
        QueryWrapper<EnterPrise> queryWrapper = new QueryWrapper<>();
        if(mobile != null) {
            queryWrapper.eq("mobile", mobile);
        }
        if(name != null) {
            queryWrapper.like("name", name);
        }
        if(StringUtils.isNotBlank(position)) {
            if (position.equals("1")) {
                queryWrapper.eq("roleid", 2);
                queryWrapper.eq("isleader", 1);
            } else if (position.equals("2")) {
                queryWrapper.eq("roleid", 2);
                queryWrapper.eq("isleader", 2);
            } else {
                queryWrapper.eq("roleid", 3);
                queryWrapper.eq("isleader", 0);
            }
        }else {
            queryWrapper.in("roleid", 2, 3);
        }
        queryWrapper.eq("delflag", 0);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null))";
                queryWrapper.apply("id in"+sql);
            }else{
                IPage<EnterPrise> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
        }
        queryWrapper.orderByDesc("createtime");
        Page<EnterPrise> page = new Page<>(pageNo, pageSize);
        IPage<EnterPrise> result = enterPriseService.page(page, queryWrapper);
        result.getRecords().forEach(enterPrise -> {
            if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 1){
                enterPrise.setPosition("1");
            }else if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 2){
                enterPrise.setPosition("2");
            }else if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 0){
                enterPrise.setPosition("0");
            }else{
                enterPrise.setPosition("3");
            }
        });
        return Result.ok(result);
    }
    @ApiOperation(value = "获取工人列表")
    @GetMapping("/list")
    public Result list() {
        QueryWrapper<EnterPrise> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("roleid", 2,3);
        queryWrapper.eq("delflag", 0);
        queryWrapper.orderByDesc("createtime");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null))";
                queryWrapper.apply("id in"+sql);
            }else{
                IPage<EnterPrise> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
        }
        List<EnterPrise> result = enterPriseService.list(queryWrapper);
        result.forEach(enterPrise -> {
            if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 1){
                enterPrise.setPosition("1");
            }else if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 2){
                enterPrise.setPosition("2");
            }else if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 0){
                enterPrise.setPosition("0");
            }else{
                enterPrise.setPosition("3");
            }
        });
        return Result.ok(result);
    }
    /**
     *   添加
     *
     * @param enterPrise
     * @return
     */
    @AutoLog(value = "工人-添加")
    @ApiOperation(value="工人-添加", notes="工人-添加")
    //@RequiresPermissions("org.jeecg.modules:enterPrise:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody EnterPrise enterPrise) {
        if (enterPriseService.getOne(new QueryWrapper<EnterPrise>().eq("mobile", enterPrise.getMobile())
            .eq("delFlag", "0")) != null) {
        return Result.error("手机号已存在");
    }
        if (enterPriseService.getOne(new QueryWrapper<EnterPrise>().eq("name", enterPrise.getName())
                .eq("delFlag", "0")) != null) {
            return Result.error("姓名已存在");
        }
        enterPrise.setId(CommonUtils.getID());
        enterPrise.setPassword(EncryptUtils.md5(CommonUtils.PWD));
        enterPrise.setCreatetime(DateUtils.getCurrentDate());
        enterPrise.setDelflag("0");//删除标识
        enterPrise.setApprove(1);
        enterPrise.setApprovetime(null);
        if(enterPrise.getPosition().equals("1")){
            enterPrise.setRoleid(2);
            enterPrise.setIsleader(1);
        }else if (enterPrise.getPosition().equals("2")){
            enterPrise.setRoleid(2);
            enterPrise.setIsleader(2);
        }else{
            enterPrise.setRoleid(3);
            enterPrise.setIsleader(0);
        }
        enterPriseService.save(enterPrise);
        return Result.OK("添加成功！");
    }
    /**
     *  编辑
     *
     * @param enterPrise
     * @return
     */
    @AutoLog(value = "工人-编辑")
    @ApiOperation(value="工人-编辑", notes="工人-编辑")
    //@RequiresPermissions("org.jeecg.modules:enterPrise:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody EnterPrise enterPrise) {
        if(enterPrise.getPosition().equals("1")){
            enterPrise.setRoleid(2);
            enterPrise.setIsleader(1);
        } else if (enterPrise.getPosition().equals("2")) {
            enterPrise.setRoleid(2);
            enterPrise.setIsleader(2);
        }
        enterPriseService.updateById(enterPrise);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "工人-通过id停用")
    @ApiOperation(value="工人-通过id停用", notes="工人-通过id停用")
    //@RequiresPermissions("org.jeecg.modules:enterPrise:delete")
    @GetMapping(value = "/stop")
    public Result<String> stop(@RequestParam(name="id",required=true) String id) {
        UpdateWrapper<EnterPrise> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("approve", 3);
        enterPriseService.update(updateWrapper);
        return Result.OK("停用成功!");
    }
    @AutoLog(value = "工人-通过id启用")
    @ApiOperation(value="工人-通过id启用", notes="工人-通过id启用")
    //@RequiresPermissions("org.jeecg.modules:enterPrise:delete")
    @GetMapping(value = "/start")
    public Result<String> start(@RequestParam(name="id",required=true) String id) {
        UpdateWrapper<EnterPrise> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("approve", 1);
        enterPriseService.update(updateWrapper);
        return Result.OK("启用成功!");
    }
    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工人-通过id删除")
    @ApiOperation(value="工人-通过id删除", notes="工人-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:enterPrise:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        UpdateWrapper<EnterPrise> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("delflag", 1);
        enterPriseService.update(updateWrapper);
        return Result.OK("删除成功!");
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工人-批量删除")
    @ApiOperation(value="工人-批量删除", notes="工人-批量删除")
    //@RequiresPermissions("org.jeecg.modules:enterPrise:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        List<String> list=Arrays.asList(ids.split(","));
        list.forEach(id->{
            UpdateWrapper<EnterPrise> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id).set("delflag", 1);
            enterPriseService.update(updateWrapper);
        });
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工人-通过id查询")
    @ApiOperation(value="工人-通过id查询", notes="工人-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<EnterPrise> queryById(@RequestParam(name="id",required=true) String id) {
        EnterPrise enterPrise = enterPriseService.getById(id);
        if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 1){
            enterPrise.setPosition("1");
        }else if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 2){
            enterPrise.setPosition("2");
        }else if(enterPrise.getRoleid() == 2&& enterPrise.getIsleader() == 0){
            enterPrise.setPosition("0");
        }else{
            enterPrise.setPosition("3");
        }
        if(enterPrise==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(enterPrise);
    }
}
